import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store'


Vue.use(VueRouter)



const routes = [
  {
    path: "/",
    // 重定向
    redirect: "/login"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    redirect: "/home/hi",
    // 配置子路由  子路由不能加/
    children: [
      {
        path: 'hi',
        name: 'hi',
        component: () => import('../components/HelloWorld.vue')
      },
      {
        path: 'index',
        name: 'index',
        component: () => import('../views/dashboard.vue')
      },
      {
        path: 'data',
        name: 'data',
        component: () => import('../views/data.vue')
      },
      {
        path: 'list',
        name: 'list',
        component: () => import('../components/list.vue')
      },
      {
        path: 'protect',
        name: 'protect',
        component: () => import('../components/protect.vue')
      },
      {
        path: 'business',
        name: 'business',
        component: () => import('../components/business.vue')
      }
    ]
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

//重写push方法
// 路由守卫拒绝跳转 重写push方法
// const org = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return org.call(this, location).catch(err => err)
// }




const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//动态路由
// addRoute
let obj = {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/login.vue')
  }
  router.addRoute(obj)

//全局路由守卫
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  //如果登录放行
  if (to.path == '/login') {
    return next()
  } else if (!token) {
    //没有token 送去登录
    return next('/') //路由跳转
  } else {
    //有token放行
    const hasName = store.state.name
    if (hasName) {
      next()
    } else {
      store.dispatch('getUserInfo')
      next()
    }
  }

})
export default router
